package com.sfac.springBoot.config.shiro;

import com.sfac.springBoot.module.account.pojo.Role;
import com.sfac.springBoot.module.account.pojo.User;
import com.sfac.springBoot.module.account.service.AccountService;
import com.sfac.springBoot.module.account.service.RoleService;
import com.sfac.springBoot.module.account.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * personal demo
 **/
@Component //只有注册为component才能使用别的bean
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;


    @Override//资源授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {

        SimpleAuthorizationInfo sai = new SimpleAuthorizationInfo();
        User user = (User) principal.getPrimaryPrincipal();
        List<Role> roles = roleService.selectRolesById(user.getId());
        roles.stream().forEach(i->{
            sai.addRole(i.getRoleName());
        });
    }
/*
*
*    ↑
*    |
*    |
  *  |
  * 下面丢什么上面拿什么
  *
* */



    @Override//身份认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();

        //查有无user
        User user = userService.selectUserByName(username);
        if(user==null){
            throw new UnknownAccountException("username or password is wrong");
        }

        //包装身份认证器，拿出加密后的密码
       return new SimpleAuthenticationInfo(user,user.getPassword(),getName());



















    }
}
